package api

import (
	"encoding/json"
	"gateway-api/basic/config"
	__ "gateway-api/basic/proto"
	"gateway-api/handler/request"
	"gateway-api/pkg"
	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
	"net/http"
	"time"
)

func Login(c *gin.Context) {
	var param request.Login
	if err := c.ShouldBind(&param); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"mes":  "参数错误",
		})
		return
	}
	r, err := config.UserCline.GetPhoneByPhone(c, &__.GetPhoneByPhoneReq{
		Phone: param.Phone,
	})
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"mes":  err.Error(),
		})
		return
	}
	token, err := pkg.NewJWT("2303A").CreateToken(pkg.CustomClaims{
		ID: uint(r.UserId),
		StandardClaims: jwt.StandardClaims{
			ExpiresAt: int64(2 * time.Hour),
		},
	})

	if r.UserId == 0 {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"mes":  "该用户不存在",
		})
		return
	}
	marshal, err := json.Marshal(r)
	config.Rdb.Set(config.Ctx, "login", marshal, time.Hour*2)
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"mes":  "登陆成功",
		"data": token,
	})
	return
}

func SendSms(c *gin.Context) {
	var param request.SendSms
	if err := c.ShouldBind(&param); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"mes":  "参数错误",
		})
		return
	}
	_, err := config.UserCline.SendSms(c, &__.SendSmsReq{
		Phone: param.Phone,
	})
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"mes":  err.Error(),
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"mes":  "验证码获取成功",
	})
	return
}
